import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '../utils/request'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  
  // 正确初始化userInfo
  let initialUserInfo = {}
  try {
    const storedInfo = localStorage.getItem('userInfo')
    if (storedInfo) {
      initialUserInfo = JSON.parse(storedInfo)
    }
  } catch (error) {
    console.error('Failed to parse userInfo from localStorage:', error)
  }
  
  const userInfo = ref(initialUserInfo)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userRole = computed(() => {
    const role = userInfo.value?.userType || ''
    return role.toLowerCase()
  })

  // 方法
  const setToken = (newToken) => {
    token.value = newToken
    if (newToken) {
      localStorage.setItem('token', newToken)
    } else {
      localStorage.removeItem('token')
    }
  }

  const setUserInfo = (info) => {
    // 确保userType字段保持一致的大小写处理（转为小写）
    if (info && info.userType) {
      info.userType = info.userType.toLowerCase()
    }
    
    userInfo.value = info
    if (info) {
      localStorage.setItem('userInfo', JSON.stringify(info))
    } else {
      localStorage.removeItem('userInfo')
    }
  }

  const login = async (credentials) => {
    try {
      const response = await request.post('/users/login', credentials)
      console.log('Login API response:', response)

      // 由于request.js中的响应拦截器已经处理了response，这里直接使用返回的数据
      if (response && response.data) {
        const userData = response.data
        if (userData.token) {
          setToken(userData.token)
        }
        
        // 确保userType字段保持一致的大小写处理（转为小写）
        if (userData.userType) {
          userData.userType = userData.userType.toLowerCase()
        }
        
        setUserInfo(userData)
      }
      return response
    } catch (error) {
      console.error('Login failed:', error)
      setToken('')
      setUserInfo(null)
      throw error
    }
  }

  const register = async (userData) => {
    try {
      const response = await request.post('/users/register', userData)
      return response
    } catch (error) {
      console.error('Registration failed:', error)
      throw error
    }
  }

  const logout = () => {
    setToken('')
    setUserInfo(null)
  }

  const getUserInfo = async () => {
    try {
      if (!userInfo.value?.userId) {
        throw new Error('用户未登录')
      }
      
      const response = await request.get(`/users/${userInfo.value.userId}/profile`)
      if (response && response.data) {
        // 保留token，因为API返回的数据中可能没有token
        const currentToken = token.value
        
        // 更新用户信息
        const userData = response.data
        
        // 确保userType字段保持一致的大小写处理（转为小写）
        if (userData.userType) {
          userData.userType = userData.userType.toLowerCase()
        }
        
        // 设置token和用户信息
        userData.token = currentToken
        setUserInfo(userData)
      }
      return response
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  const updateProfile = async (profileData) => {
    try {
      const response = await request.put(`/users/${userInfo.value?.userId}`, profileData)
      if (response?.data) {
        // 更新本地用户信息
        await getUserInfo()
      }
      return response
    } catch (error) {
      console.error('Profile update failed:', error)
      throw error
    }
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    userRole,
    login,
    register,
    logout,
    getUserInfo,
    updateProfile,
    setToken,
    setUserInfo
  }
}) 